package com.example.iotest.bio.piped;

import java.io.*;


/**
 * 管道流通信核心是,Writer和Reader公用一块缓冲区,缓冲区在Reader中申请,
 * 由Writer调用和它绑定的Reader的Receive方法进行写.
 * <p>
 * 线程间通过管道流通信的步骤为
 * 1 建立输入输出流
 * 2 绑定输入输出流
 * 3 Writer写
 * 4 Reader读
 */
public class PipedTest {
    public static void main(String[] args) throws InterruptedException, IOException {
        PipedOutputStream pipedOutputStream = new PipedOutputStream();
        PipedInputStream pipedInputStream = new PipedInputStream();


        new Thread(() -> {
            FileInputStream fileInputStream = null;
            try {
                pipedOutputStream.connect(pipedInputStream);
                fileInputStream= new FileInputStream("src/main/resources/files/1.txt");
                byte[] buffer=new byte[1024];
                while ((fileInputStream.read(buffer)) != -1) {
                    pipedOutputStream.write(buffer);
                }
                pipedOutputStream.write("hello".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                /*try {
                    pipedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }*/
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


        new Thread(() -> {
            try {
                byte[] buffer = new byte[1024];
                int length=0;
                while ((length=pipedInputStream.read(buffer))!=-1){
                    System.out.println("Input "+new String(buffer,0,length));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                /*try {
                    pipedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }*/
            }
        }).start();
        Thread.sleep(100);
        pipedOutputStream.close();
        pipedInputStream.close();
    }
}
